package org.linlinjava.litemall.wx.util;


import com.xiaoleilu.hutool.util.ReflectUtil;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;

@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class, Integer.class })
})
public class MerchantPermissionInterceptor implements Interceptor {
    private static final Logger log = LoggerFactory.getLogger(MerchantPermissionInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        RoutingStatementHandler handler = (RoutingStatementHandler) invocation.getTarget();

        StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(handler, "delegate");
        BoundSql boundSql = delegate.getBoundSql();
        Object params = boundSql.getParameterObject();

        MappedStatement mappedStatement = (MappedStatement) ReflectUtil
                .getFieldValue(delegate, "mappedStatement");
        Connection connection = (Connection) invocation.getArgs()[0];
        String sql = boundSql.getSql();

        StringBuilder sbSql = new StringBuilder("select * from (")
                .append(sql)
                .append(" ) s ")
                .append(" where s.merchant_id = "+ "1" +" ");

        // ReflectUtil.setFieldValue(boundSql, "sql", sbSql.toString());

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof RoutingStatementHandler) {
            return Plugin.wrap(target, this);
        }

        return target;
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
